package com.sunday.common.http.vertx;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Launcher;
import io.vertx.core.buffer.Buffer;
import io.vertx.ext.web.client.HttpResponse;
import io.vertx.ext.web.client.WebClient;
import lombok.extern.slf4j.Slf4j;


/**
 * 创建 Web 客户端
 * https://vertx.io/docs/vertx-web-client/java/
 */
@Slf4j
public class Client extends AbstractVerticle {

    public static void main(String[] args) {
        Launcher.executeCommand("run", Client.class.getName());
    }

    @Override
    public void start() throws Exception {

        WebClient client = WebClient.create(vertx);
        baidu(client);
        local(client);

    }

    protected void local(WebClient client) {
        client.get(8080, "localhost", "/base")
                .send(ar -> {
                    if (ar.succeeded()) {
                        HttpResponse<Buffer> response = ar.result();
                        log.info("Got HTTP response with status {}", response.statusCode());
                        log.info("Got HTTP response with body {}", response.bodyAsString());
                    } else {
                        ar.cause().printStackTrace();
                    }
                });
    }

    protected void baidu(WebClient client) {
        client.get(80, "www.baidu.com", "/")
                .send(ar -> {
                    if (ar.succeeded()) {
                        HttpResponse<Buffer> response = ar.result();
                        log.info("Got HTTP response with status {}", response.statusCode());
                        log.info("Got HTTP response with body {}", response.bodyAsString());
                    } else {
                        ar.cause().printStackTrace();
                    }
                });
    }
}
